<template>
  <!-- 车辆库存 > 车辆库存查询 -->
  <div>
    <TopFilter
      ref="formpanel"
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <div style="position: relative">
      <div
      :style="{
          'display': 'flex',
          'align-items': 'center',
          'position': 'absolute',
          'left': '220px'
        }"
      >
        <el-button size="small" type="primary"  :loading="exportLoading" @click="addHandle">导出</el-button>
        <div :style="{
            'font-weight': 'bold',
            'padding': '0 10px',
            'padding-right': '88px'
          }"
        >
          <span> 在库车辆总数: {{vehicleNum.vehicleTotal}}  </span>
          <span> 库龄1个月数量: {{vehicleNum.oneMonthNum}}  </span>
          <span> 库龄2个月数量: {{vehicleNum.twoMonthNum}}  </span>
          <span> 库龄3个月数量: {{vehicleNum.threeMonthNum}}  </span>
          <span> 库龄大于3个月数量: {{vehicleNum.threePlusMonthNum}}  </span>
        </div>
      </div>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onColumnsChange="columns => this.columns = columns"
    >
    </FilterTable>
    </div>
    <BaseDialog
        :visible.sync="visible"
        :title="dialogTitle"
        destroyOnClose
        :width="dialogWidth"
        :containerStyle="{height: '100%', overflow: 'auto'}">
        <InventoryDetail :type="handleType" :rowData="formData" @close="closeHandler"></InventoryDetail>
    </BaseDialog>
    <!-- <Drawer
		  :visible.sync="visible"
		  title="车辆库存明细"
      width="1000px"
      destroyOnClose
		>
		  <InventoryDetail :type="handleType" :rowData="formData" @close="closeHandler"></InventoryDetail>
		</Drawer> -->

  </div>
</template>

<script>
import { getVsStock, getVehicleNum, qryVsStockPage } from '@/api/vehicle/stockmanage/InventoryMaintenance';
import { vehicleConfiguration,queryVsStoreAll } from '@/api/retail/salesmanage/confirmcar'; //获取五级菜单
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils/index';
import InventoryDetail from './InventoryDetail';
import moment from 'moment';
export default {
  name: 'InventoryMaintenance',
  mixins: [dictionary],
  components: {
    InventoryDetail
  },
  data() {
    return {
      topFilterList: this.createTopFilters(),
      fetchParams: {},
      visible: false,
      dialogTitle: '车辆库存明细',
      dialogWidth: '70%',
      fetchApi: getVsStock,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      conf:{ add: '新增', edit: '编辑', show: '显示' },
      vehicleNum: {}, // 车辆统计
      exportLoading: false,
      carNameItem:null,
    };
  },
  methods: {
    init () {
      vehicleConfiguration(0, {
        isUnlimited: 10041001
      }).then( res => {
        // 与产品配置在topFilterList的位置有关
        this.topFilterList[5].itemList = res.data;
      }).catch( err => {
        // console.log(err)
      })

      queryVsStoreAll().then(res=>{
        if(res.success){
          res.data.forEach(x=>{
            this.topFilterList.find(x=>x.fieldName == 'storageName').itemList.push({text:x.storageName ,value:x.storageCode})
          })
        }
      })
    },
    createTopFilters () {
      return [
        {
          type: 'SELECT',
          label: '仓库名称',
          fieldName: 'storageName',
          placeholder: '请输入...',
          itemList:[],
        },
        {
          type: 'SELECT',
          label: '库存状态',
          fieldName: 'ownStockStatus',
          placeholder: '请选择',
          itemList: this.createDictList('1413')
        },
        {
          type: 'SELECT',
          label: '配车状态',
          fieldName: 'dispatchedStatus',
          placeholder: '请选择',
          itemList: this.createDictList('1414').filter( x=> [14141001,14141002].includes(x.value))
        },
        {
          type: 'INPUT',
          label: '产品代码',
          fieldName: 'productCode',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT_CASCADER',
          label: '产品配置',
          fieldName: 'carName',
          placeholder: '请选择',
          options:{ titles: ['品牌', '车系', '车型', '配置', '颜色'] }, // TODO:
          change:(val,ref, item)=>{
            // console.log(val,"产品配置")
            console.log(item,"产品配置item")
            this.carNameItem = item
          },
          itemList:[{
            text: '一级分类1',
            value: '1',
            children: []
          }]
        },
        {
          type: 'RANGE_DATE',
          label: '入库日期',
          fieldName: 'latestStockInDateStart|latestStockInDateEnd',
          placeholder: '请选择'
        },
        {
          type: 'RANGE_DATE',
          label: '出库日期',
          style: {overflow: 'hidden'}, // 避免左侧边框被遮挡
          fieldName: 'latestStockOutDateStart|latestStockOutDateEnd',
          placeholder: '请选择'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.detailFun(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '库龄(天)',
          dataIndex: 'stockAge',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '库存状态',
          dataIndex: 'ownStockStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1413'),
          render: props => {
            return <span>{ this.preDictHandler(props.row.ownStockStatus, '1413') }</span>;
          }
        },
        {
          title: '配车状态',
          dataIndex: 'dispatchedStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',// TODO: 数据有误，字典来源不一致
          filterItems: this.createDictList('1414').filter( x => [14141001,14141002].includes(x.value)),
          render: props => {
            return <span>{ this.preDictHandler(props.row.dispatchedStatus, '1414') }</span>;
          }
        },
        {
          title: '产品代码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '仓库名称',
          dataIndex: 'storageName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '是否锁定',
          dataIndex: 'isLock',
          sorter: true,
          filter: true,
          filterType: 'checkbox', // TODO: 数据有误，字典来源不一致
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{ this.preDictHandler(props.row.isLock, '1004') }</span>;
          }
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置',
          dataIndex: 'packageName', //TODO:packageName
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '颜色',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰色',
          dataIndex: 'trimColor', //TODO: trimColor
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车厂指导价',
          dataIndex: 'oemDirectivePrice', //TODO: oemDirectivePrice
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售指导价',
          dataIndex: 'directivePrice', //TODO: directivePrice
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '库位',
          dataIndex: 'storagePositionCode', //TODO:storagePositionCode
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '入库类型',
          dataIndex: 'entryType',
          sorter: true,
          filter: true,
          filterType: 'checkbox', //TODO:数据有误，字典来源不一致
          filterItems: this.createDictList('1317'),
          render: props => {
            return <span>{ this.preDictHandler(props.row.entryType, '1317') }</span>;
          }
        },
        {
          title: '首次入库日期',
          dataIndex: 'firstStockInDate',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props =>{
            return <span>{ this.preDateHandler(props.row.firstStockInDate,'YYYY-MM-DD') } </span>;
          }
        },
        {
          title: '入库日期',
          dataIndex: 'latestStockInDate',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props =>{
            return <span>{ this.preDateHandler(props.row.latestStockInDate,'YYYY-MM-DD') } </span>;
          }
        },
        {
          title: '出库类型',
          dataIndex: 'deliveryType', //TODO:deliveryType
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1318'),
          render: props => {
            return <span>{ this.preDictHandler(props.row.deliveryType, '1318') }</span>;
          }
        },
        {
          title: '出库日期',
          dataIndex: 'latestStockOutDate',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props =>{
            return <span>{ this.preDateHandler(props.row.latestStockOutDate,'YYYY-MM-DD') } </span>;
          }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          showOverflowTooltip:true,
          filterType: 'input'
        }
      ];
    },
    addHandle() {
      this.$refs.formpanel.SUBMIT_FORM();
      this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
	        confirmButtonText: '下载',
	        cancelButtonText: '取消',
	        type: 'warning'
	      }).then(() => {
          let params = {
            carName: '',
            dispatchedStatus: '',
            latestStockInDateEnd: '',
            latestStockInDateStart: '',
            latestStockOutDateEnd: '',
            latestStockOutDateStart: '',
            ownStockStatus: '',
            productCode: '',
            storageName: '',
            vin: '',
          }
          for(let item in params){
            params[item] = this.fetchParams[item]
          }
          this.exportLoading = true
          qryVsStockPage(params).then( response => {
            console.log(response,"车辆库存")
            exportExcelFile(response.data,'车辆库存');
            this.exportLoading = false;
          }).catch( err => {
            console.log(err)
          })
	      }).catch(() => {
	        this.$message({
	          type: 'info',
	          message: '已取消'
	        });
	      });
    },
    // 字典数据使用前预处理
    preDictHandler(val, code){
      let resultText = val && String.prototype.includes.call(val, code) ? this.createDictText(val, code) : val;
      return resultText;
    },
    // 日期预处理
    preDateHandler(val, formatCode='YYYY-MM-DD HH:mm:ss') {
      let resultDate = val ? moment(Number(val)).format(formatCode) : val;
      return resultDate;
    },
    detailFun(row) {
      //TODO:查看
      this.visible = true;
      this.handleType = 'show';
      this.formData = row;
    },
    changeHandle(fetchParams) {
      console.log(fetchParams.carName,"fetchParams.carName")
      if(fetchParams.carName){
        let carNameValue = fetchParams.carName.split(",")[fetchParams.carName.split(",").length-1]
        let productId = ""
        this.carNameItem.forEach(x=>{
            if(x.value == carNameValue){
              productId = x.productId
            }
        })
        if(productId){
          fetchParams.carName+=`,${productId}`
        }
        let carNameProductId = ""
        fetchParams.carName.split(",").forEach(x=>{
            if(x != carNameValue){
              carNameProductId+=x+','
            }
        })
        // console.log(carNameProductId,"carNameProductId",carNameProductId.slice(0,carNameProductId.lastIndexOf(",")))
        fetchParams.carName = carNameProductId.slice(0,carNameProductId.lastIndexOf(","))
      }
      // if(val.carName){
      //   let cifg = val.carName.split(',')
      //   let configure = {
      //     brandCode: cifg[0],
      //     seriesId: cifg[1],
      //     modelId: cifg[2],
      //     packageId: cifg[3],
      //     colorCode: cifg[4]
      //   }
      //   val = {...val, ...configure}
      // }
      // console.log(val)
      this.fetchParams = Object.assign({}, fetchParams);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    getVehicleNum().then(response => {
      this.vehicleNum = response.data
    });
  },
  created() {
    this.init();
  }
};
</script>

<style lang="less" scoped>
</style>
